package com.dating.beetl.tags;

import java.io.IOException;
import java.util.List;

import org.beetl.core.Tag;
import org.nutz.lang.Lang;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;

import com.dating.base.bean.User;
import com.dating.base.dto.Menu;
import com.dating.base.vo.SystemSetting;
import com.dating.utils.StrKit;

public class MenuTag extends Tag{
	
	private static final Log LOG = Logs.getLog(MenuTag.class);
	
	protected String base = Mvcs.getReq().getAttribute("base").toString();
	
	
	@Override
	public void render() {
		
		User user = (User)Mvcs.getReq().getSession().getAttribute(SystemSetting.SESSION_USER_KEY);
		@SuppressWarnings("unchecked")
		List<Menu> userMenus = (List<Menu>)Mvcs.getReq().getSession().getAttribute("userMenus");
		StringBuilder menuhtml = new StringBuilder();
		if(user != null){
			
			try
            {
				for (Menu menu : userMenus) {
					menuhtml.append(renderMenu(menu));
				}
				this.ctx.byteWriter.writeString(menuhtml.toString());
            }
            catch (IOException e)
            {
            	LOG.error(e);
            }
			
			
			
		}
	}
	
	private String renderMenu(Menu menu){
		StringBuilder sb = new StringBuilder();
		sb.append("<li data-key='"+ menu.getName() +"'>");
		if(Lang.isEmpty(menu.getSubMenus())){
			sb.append("<a href="+ base + "/" +menu.getUrl()+"><i class='menu-icon fa fa-"+menu.getIcon()+"'></i><span class='menu-text'>"+menu.getDesc()+"</span></a><b class='arrow'></b>");
		}else{
			sb.append("<a href='"+ (StrKit.isBlank(menu.getUrl()) ? "###" : (base + "/" + menu.getUrl())) + "' class='dropdown-toggle'>");
			sb.append("<i class='menu-icon fa fa-"+menu.getIcon()+"'></i><span class='menu-text'>"+ menu.getDesc() +"</span><b class='arrow fa fa-angle-down'></b></a>");
			sb.append("<ul class='submenu'>");
			for (Menu submenu : menu.getSubMenus()) {
				sb.append(renderMenu(submenu));
			}
			sb.append("</ul>");
		}
		sb.append("</li>");
		return sb.toString();
	}
	
}
